import uploadFile from './upload'
const formatTime = (date, option) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  //获取 年月日
  if (option == 'YY-MM-DD') return [year, month, day].map(formatNumber).join('-')

  //获取 年月
  if (option == 'YY-MM') return [year, month].map(formatNumber).join('-')

  //获取 年
  if (option == 'YY') return [year].map(formatNumber).toString()

  //获取 月
  if (option == 'MM') return [mont].map(formatNumber).toString()

  //获取 日
  if (option == 'DD') return [day].map(formatNumber).toString()
  //获取 时分秒
  if (option == 'hh-mm-ss') return [hour, minute, second].map(formatNumber).join(':')

  //获取 时分
  if (option == 'hh-mm') return [hour, minute].map(formatNumber).join(':')

  //获取 分秒
  if (option == 'mm-dd') return [minute, second].map(formatNumber).join(':')

  //获取 时
  if (option == 'hh') return [hour].map(formatNumber).toString()

  //获取 分
  if (option == 'mm') return [minute].map(formatNumber).toString()

  //获取 秒
  if (option == 'ss') return [second].map(formatNumber).toString()

  //默认 年月日 时分秒 
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function uploadImage(count) {
  return new Promise((resolve, reject) => {
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res.tempFilePaths
        resolve(filePath)
      }
    });
  })

}

function returnLabel(item) {
  let array = []
  if (item.isProject985 === 1) {
    array.push('985')
  }
  if (item.isProject211 === 1) {
    array.push('211')
  }
  if (item.isDoubleTop === 1) {
    array.push('双一流')
  }
  if (item.isStrongPlan === 1) {
    array.push('强基计划')
  }
  if (item.isDoubleHighPlan === 1) {
    array.push('双高计划')
  }
  item['filter'] = array
  return array
}
//审核内容
function checkContent(content) {
  wx.showLoading({
    title: '发布中',
  })
  return new Promise((resolve, reject) => {
    wx.cloud.callFunction({
      name: 'contentCheck',
      data: {
        'content': content
      }
    }).then(res => {
      wx.hideLoading()
      //获取状态码  0 》》》正常   87014》》》违规
      const {
        errCode
      } = res.result
      if (errCode != 0) {
        wx.showToast({
          title: '提交内容含敏感词，请重新输入',
          icon: 'none'
        })
        reject()
      } else {
        resolve()
      }
    })
  })

}

function checkImg(images) {
  //上传图片到云存储
  wx.showLoading({
    title: '图片审核中',
  })
  let promiseArr = [];
  return new Promise((resolve, reject) => {
    for (var i = 0; i < images.length; i++) {
      promiseArr.push(new Promise((success, reject) => {
        let item = images[i];
        let suffix = /\.\w+$/.exec(item)[0];
        wx.cloud.uploadFile({
          cloudPath: '动态图片' + new Date().getTime() + suffix, // 上传至云端的路径
          filePath: item, // 小程序临时文件路径
          success: res => {
            wx.cloud.callFunction({
              name: 'checkImg',
              data: {
                contentType: 'image/jpg',
                fileID: res.fileID
              }
            }).then(data => {
              console.log(res, data)
              if (data.result.errCode !== 0) {
                wx.hideLoading()
                wx.showToast({
                  title: '图片内容不符合审核要求',
                  icon: 'none'
                })
                reject()
              }
              success()
            })
          },
          fail: res => {
            wx.hideLoading();
            wx.showToast({
              title: "上传失败",
            })
          }
        })
      }))
    }
    Promise.all(promiseArr).then(res => {
      wx.hideLoading();
      resolve()
    })
  })


}
//上传图片至阿里云
// https://ehsimg.oss-cn-beijing.aliyuncs.com/images/volunteer/analyse_bg.png

function uploadPic(filePath, index) {
  var that = this
  wx.showLoading({
    title: '上传中',
    mask: true
  })
  let suffix = /\.\w+$/.exec(filePath);
  // const fileName='static/users/shareImg'+suffix

  const fileName = new Date().getTime() + suffix

  return new Promise((resolve, reject) => {
    uploadFile(filePath, 'images/' + fileName,
      function (result) {
        wx.hideLoading()
        resolve(result)
      },
      function (result) {
        wx.hideLoading()
        reject(result)
      }
    )
  })
  //静态图片上传
  const name = ''
  return new Promise((resolve, reject) => {
    uploadFile(filePath, 'images/static/' + name + suffix,
      function (result) {
        wx.hideLoading()
        resolve(result)
      },
      function (result) {
        wx.hideLoading()
        reject(result)
      }
    )
  })

}
const imageToBase64 = function (img) {
  return new Promise(((resolve, reject) => {
    wx.downloadFile({
      url: img,
      success(res) {
        wx.getFileSystemManager().readFile({
          filePath: res.tempFilePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            resolve('data:image/png;base64,' + res.data)
          }
        })
      }
    })

  }))
}
//压缩  
const cutBase64 = (urls, canvasId, index, setCanvas, callback, type) => {
  if (index == urls.length) {
    return;
  }
  wx.showLoading({
    title: '上传中',
  })
  wx.getImageInfo({
    src: urls[index],
    success: (res) => {
      // 设置初始裁剪比例，当图片大小大于设置阈值时，则对图片长宽按次比例进行裁剪
      let ratio = 2;
      let canvasWidth = res.width;
      let canvasHeight = res.height;
      // 根据比例对图片长宽进行裁剪，若裁剪后图片大小依然大于设置阈值时，则提高裁剪比例继续对图片进行裁剪
      // 此处假定需要将图片裁剪至200kb以内，因此 阈值 = 200 * 1024 = 204800
      while (canvasWidth > 200 || canvasHeight > 200) { // 保证宽高在200以内
        canvasWidth = Math.trunc(res.width / ratio)
        canvasHeight = Math.trunc(res.height / ratio)
        ratio++;
      }
      // 调用setCanvas()方法设置canvas的长宽，设置完成后开始绘图，否则可能会出现"fail canvas is empty"的错误
      setCanvas(canvasWidth, canvasHeight, () => {
        // 获取canvasId对应的绘图上下文对象
        let ctx = wx.createCanvasContext(canvasId);
        ctx.drawImage(urls[index], 0, 0, canvasWidth, canvasHeight);
        // draw()的第一个参数为false表示不保留canvas上一次的绘制结果
        // 这里设置100毫秒的延迟是为了在canvas绘图完成后再获取图片信息，否则获取到的图片可能是空白
        ctx.draw(false, setTimeout(() => {
          // 获取canvas绘制内容并转为图片
          wx.canvasToTempFilePath({
            canvasId: canvasId,
            destWidth: canvasWidth,
            destHeight: canvasHeight,
            quality: 0.1,
            success: res => {
              // 图片导出成功后调用回调
              callback(res.tempFilePath, index, type);
              // 进行下一次递归，由于此时canvas的绘制与图片的导出都已经结束了，因此不会对canvas后续的绘制、导出产生影响
              cutBase64(urls, canvasId, ++index, setCanvas, callback);
            }
          })
        }, 100));
      });
    }
  })
  // 根据urls及index获取图片信息

}
//
function complete(filepath) {
  //上传图片到云存储
  wx.showLoading({
    title: '图片审核中',
  })
  let promiseArr = [];
  const that = this;
  let item = filepath;
  console.log(filepath)
  let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
  wx.cloud.uploadFile({
    cloudPath: '动态图片' + new Date().getTime() + suffix, // 上传至云端的路径
    filePath: item, // 小程序临时文件路径
    success: res => {
      console.log(res) //输出上传后图片的返回地址
      wx.cloud.callFunction({
        name: 'checkImg',
        data: {
          contentType: 'image/jpg',
          fileID: res.fileID
        }
      }).then(res => {
        if (res.result.errCode == 0) {
          wx.showToast({
            title: '审核通过',
            icon: 'none'
          })
          wx.hideLoading()
          that.upload()
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '图片内容不符合审核要求',
            icon: 'none'
          })
        }
      }).catch(err => {
        // reslove(true)
        wx.hideLoading()
        console.log(err)
      })
    },
    fail: res => {
      wx.hideLoading();
      wx.showToast({
        title: "上传失败",
      })
    }
  })
}

function getLoginCode() {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        // 这里也可以选择性返回需要的字段
        resolve(res.code)
      },
      fail(res) {
        reject(res);
      }
    })
  })
}

function checkLogin() {
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync('token');
    if (!token) {
      wx.removeStorageSync('token')
      reject()
    } else {
      resolve(true)
    }
  })
}

function checkProfile() {
  return new Promise((resolve, reject) => {
    let avatar = wx.getStorageSync('userInfo').avatar
    let nickname = wx.getStorageSync('userInfo').nickname
    let mobile = wx.getStorageSync('userInfo').mobile
    if (avatar.indexOf('ehsimg.oss-cn-beijing.aliyuncs.com') < 0 && nickname.indexOf('微信用户') > -1 && !mobile) {
      reject()
    } else {
      resolve(true)
    }
  })
}
const contactUrlParams = (o) => {
  let arr = [];
  Object.keys(o).forEach((key) => {
    arr.push(`${key}=${o[key]}`);
  });
  return "?" + arr.join("&");
}
/* 节流函数封装 */
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }
  let _lastTime = null
  // 返回新的函数
  return function () {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
/* 防抖函数封装 */
function debounce(fn, interval) {
  let timer;
  let delay = interval || 1000; // 间隔的时间，如果interval不传，则默认1秒
  return function () {
    let that = this;
    let args = arguments; // 保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      fn.apply(that, args); // 用apply指向调用debounce的对象，相当于this.fn(args);
    }, delay);
  };
}

function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return
  }
  for (let key in obj) {
    if (obj.hasOwnProperty(key) && (obj[key] == null || obj[key] == undefined || obj[key] === '' || obj[key] === 0 || obj[key].length <= 0)) {
      delete obj[key]
    }
  }
  return obj
}

function commentTimeHandle(time) {
  var publishTime = new Date(time).getTime() / 1000,
    date = new Date(publishTime), //获取dateStr的标准格式 console.log(date) 打印结果  Thu Sep 06 2018 18:47:00 GMT+0800 (中国标准时间)
    dates=new Date(new Date(time).getTime()),
    // 获取date 中的 年 月 日 时 分 秒
    Y = dates.getFullYear(),
    M = dates.getMonth() + 1,
    D = dates.getDate(),
    H = date.getHours(),
    m = date.getMinutes(),
    s = date.getSeconds();
  // 对 月 日 时 分 秒 小于10时, 加0显示 例如: 09-09 09:01
  if (M < 10) {
    M = '0' + M;
  }
  if (D < 10) {
    D = '0' + D;
  }
  if (H < 10) {
    H = '0' + H;
  }
  if (m < 10) {
    m = '0' + m;
  }
  if (s < 10) {
    s = '0' + s;
  }
  var nowTime = new Date().getTime() / 1000, //获取此时此刻日期的秒数
    diffValue = nowTime - publishTime, // 获取此时 秒数 与 要处理的日期秒数 之间的差值
    diff_days = parseInt(diffValue / 86400), // 一天86400秒 获取相差的天数 取整
    diff_hours = parseInt(diffValue / 3600), // 一时3600秒
    diff_minutes = parseInt(diffValue / 60),
    diff_secodes = parseInt(diffValue);
  if (diff_days > 0 && diff_days < 3) { //相差天数 0 < diff_days < 3 时, 直接返出
    return diff_days + "天前";
  } else if (diff_days <= 0 && diff_hours > 0) {
    return diff_hours + "小时前";
  } else if (diff_hours <= 0 && diff_minutes > 0) {
    return diff_minutes + "分钟前";
  } else if (diff_secodes < 60) {
    if (diff_secodes <= 0) {
      return "刚刚";
    } else {
      return diff_secodes + "秒前";
    }
  } else if (diff_days >= 3 && diff_days < 30) {
    return M + '-' + D + ' ' + H + ':' + m;
  } else if (diff_days >= 30) {
    return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
  }
}
// px 转换为 rpx ，传参类型是数字（Number）

function pxTorpx(px) {

  let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度

  let rpx = (750 / deviceWidth) * Number(px)

  return Math.floor(rpx);

}

function rpxTopx(rpx) {

  let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度

  let px = rpx * (deviceWidth / 750);

  return Math.floor(px);

}

function message(isModal,temIds, title, callback) {
  //支付或直接点击调用
  if (isModal) {
    wx.showModal({
      content: title,
      confirmText: '授权',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: temIds,
            success(res) {
              callback()
            },
            fail: (err) => {
              callback()
            }
          }, )
        }
      }
    })
  } else {
    wx.requestSubscribeMessage({
      tmplIds: temIds,
      success(res) {
        callback()
      },
      fail: (err) => {
        callback()
      }
    }, )
  }

}
function canParseToJson(str, parseFlag){
  try{
      if(typeof JSON.parse(str)==="object" && Object.prototype.toString.call(JSON.parse(str))==="[object Object]"){
          return parseFlag===true?JSON.parse(str) : true
      }
  }catch(e){}
  return false
}
  /**
   * 将小程序的API封装成支持Promise的API
   * @params fn {Function} 小程序原始API，如wx.login
   */
  const wxPromisify = fn => {
    return function (obj = {}) {
      return new Promise((resolve, reject) => {
        obj.success = function (res) {
          resolve(res)
        }

        obj.fail = function (res) {
          reject(res)
        }

        fn(obj)
      })
    }
  }
module.exports = {
  canParseToJson,
  pxTorpx,
  rpxTopx,
  wxPromisify:wxPromisify,
  checkLogin,
  timeago: commentTimeHandle,
  message: message,
  checkProfile,
  uploadImage,
  checkContent,
  cutBase64,
  imageToBase64,
  contactUrlParams,
  uploadPic,
  checkImg,
  getLoginCode,
  throttle,
  debounce,
  filterObj,
  returnLabel,
  formatTime
}